import { config } from './config.js';
import express from 'express';
import cors from 'cors';
import ResponseFormatter from './utils/ResponseFormatter.js';

// 导入中间件系统
import { 
    initializeMiddlewares, 
    getGlobalMiddlewares, 
    getErrorHandler, 
    getNotFoundHandler,
    middlewareConfig
} from './middleware/index.js';

// 导入API路由
import userRoutes from './api/userRoutes.js';
import productRoutes from './api/productRoutes.js';

// 异步启动函数
async function startServer() {
    const app = express();

    // 使用环境配置
    const port = config.port;
    const host = config.host;

    // 基础Express中间件配置
    app.use(express.json({ limit: '10mb' }));
    app.use(express.urlencoded({ extended: true, limit: '10mb' }));

    // CORS配置
    app.use(cors({
        origin: config.cors.origin,
        credentials: config.cors.credentials,
        methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        allowedHeaders: ['Content-Type', 'Authorization']
    }));

    // 初始化中间件系统
    await initializeMiddlewares();

    // 应用全局中间件（按优先级顺序）
     const globalMiddlewares = getGlobalMiddlewares();
     globalMiddlewares.forEach(middleware => {
         app.use(middleware);
     });

     // 基础路由
     app.get('/', (req, res) => {
         const data = {
             service: 'MihuPig API Server',
             environment: config.env,
             version: '1.0.0',
             endpoints: {
                 health: '/health',
                 users: '/api/users',
                 products: '/api/products'
             }
         };
         ResponseFormatter.success(res, data, 'Welcome to MihuPig API');
     });

     // 健康检查路由
     app.get('/health', (req, res) => {
         const healthData = {
             status: 'OK',
             environment: config.env,
             uptime: Math.floor(process.uptime()),
             memory: {
                 used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + 'MB',
                 total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024) + 'MB'
             }
         };
         ResponseFormatter.success(res, healthData, 'Service is healthy');
     });

     // API路由注册
     app.use('/api/users', userRoutes);
     app.use('/api/products', productRoutes);

     // 配置信息路由（仅开发环境）
     if (config.env === 'development') {
         app.get('/config', (req, res) => {
             // 隐藏敏感信息
             const safeConfig = {
                 ...config,
                 database: {
                     ...config.database,
                     password: '***'
                 },
                 jwt: {
                     ...config.jwt,
                     secret: '***'
                 },
                 redis: {
                     ...config.redis,
                     password: config.redis.password ? '***' : null
                 }
             };
             ResponseFormatter.success(res, safeConfig, 'Configuration information (development only)');
         });
     }

     // 404错误处理中间件（使用中间件系统）
     app.use(getNotFoundHandler());

     // 全局错误处理中间件（使用中间件系统）
     app.use(getErrorHandler());

    // 启动服务器
    app.listen(port, host, () => {
        const serverInfo = {
            server: `http://${host}:${port}`,
            environment: config.env,
            database: config.database.name,
            nodeVersion: process.version,
            apiEndpoints: `http://${host}:${port}/api`,
            timestamp: new Date().toISOString()
        };
        
        console.log('\n🚀 MihuPig API Server Started Successfully!');
        console.log('=' .repeat(50));
        console.log(`📍 Server URL: ${serverInfo.server}`);
        console.log(`📦 Environment: ${serverInfo.environment}`);
        console.log(`🗄️  Database: ${serverInfo.database}`);
        console.log(`🔧 Node.js: ${serverInfo.nodeVersion}`);
        console.log(`📡 API Base: ${serverInfo.apiEndpoints}`);
        console.log('=' .repeat(50));
        console.log('Available endpoints:');
        console.log('  GET  /           - API information');
        console.log('  GET  /health     - Health check');
        console.log('  *    /api/users  - User management');
        console.log('  *    /api/products - Product management');
        if (config.env === 'development') {
            console.log('  GET  /config     - Configuration (dev only)');
        }
        console.log('=' .repeat(50) + '\n');
        
        // 打印中间件统计信息
        const stats = middlewareConfig.getStats();
        console.log('📊 Middleware Statistics:');
        console.log(`  Total middlewares: ${stats.totalMiddlewares}`);
        console.log(`  Enabled middlewares: ${stats.enabledMiddlewares}`);
        console.log('=' .repeat(50) + '\n');
    });
}

// 启动服务器并处理错误
startServer().catch(error => {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
});
